var self = null;
cc.Class({
  extends: cc.Component,

  properties: {
    ranklistView: cc.Node,
    peoplePrefab: cc.Prefab
  },

  onLoad() {},

  start() {
    // 打开排行榜
    this.max_score = 0;
    self = this;
    // this.cached_scroll_item = [];
    this.cached_data = {};
    if (cc.sys.platform == cc.sys.WECHAT_GAME) {
      //这里的回调函数必须写在这里，提取出来，this捕获不了
      wx.onMessage(data => {
        console.log('子域中进行方法的执行', data);
        // 接收主域中传递来的值并执行对应的操作
        if (data['type'] == 'updateMaxScore') {
          // 更新当前用户最高峰
          var score = data['data'];
          // self.refresh(score);
          if (score > self.max_score) {
            self.max_score = score;
            wx.setUserCloudStorage({
              KVDataList: [{ key: 'max_score', value: parseInt(score) }],
              success: self.set_data_success,
              fail: self.set_data_fail
            });
          }
        } else if (data['type'] == 'updateMoney') {
          // 更新用户游戏货币余额
          let value = data['data'];
          wx.setUserCloudStorage({
            KVDataList: [{ key: 'user_money', value: Number(value) }],
            success: self.set_data_success,
            fail: self.set_data_fail
          });
        } else if (data['type'] == 'open') {
          // 打开排行榜
          // console.log(this);
          this.showRankList();
        }
      });
      // wx.getUserCloudStorage({
      //   keyList: ['max_score'],
      //   success: this.get_user_data_success,
      //   fail: this.get_user_data_fail
      // });
      // wx.getFriendCloudStorage({
      //   keyList: ['user_money'],
      //   success: this.get_friend_data_success,
      //   fail: this.get_friend_data_fail
      // });
    }
  },

  showRankList() {
    wx.getFriendCloudStorage({
      keyList: ['user_money'],
      success: this.get_friend_data_success(this),
      fail: this.get_friend_data_fail
    });
  },

  on_message_come: data => {
    // 接收主域中传递来的值并执行对应的操作
    if (data['type'] == 'updateMaxScore') {
      // 更新当前用户最高峰
      var score = data['data'];
      // self.refresh(score);
      if (score > self.max_score) {
        self.max_score = score;
        wx.setUserCloudStorage({
          KVDataList: [{ key: 'max_score', value: parseInt(score) }],
          success: self.set_data_success,
          fail: self.set_data_fail
        });
      }
    } else if (data['type'] == 'updateMoney') {
      // 更新用户游戏货币余额
      let data = data['data'];
      wx.setUserCloudStorage({
        KVDataList: [{ key: 'user_money', value: Number(data) }],
        success: self.set_data_success,
        fail: self.set_data_fail
      });
    } else if (data['type'] == 'open') {
      // 打开排行榜
      this.showRankList();
    }
  },

  // refresh: function(score) {
  //   this.score_num_txt.string = score;
  //   if (score > this.max_score) {
  //     this.max_score_notice.active = true;
  //   } else {
  //     this.max_score_notice.active = false;
  //   }
  //   var items_d = [];
  //   for (var k in this.cached_data) {
  //     items_d.push(this.cached_data[k]);
  //   }
  //   items_d.sort(function(a, b) {
  //     return b['max_score'] - a['max_score'];
  //   });
  //   for (var i = 0; i < items_d.length; i++) {
  //     if (i < this.cached_scroll_item.length) {
  //       this.cached_scroll_item[i].refresh(i, items_d[i]);
  //     } else {
  //       var new_node = cc.instantiate(this.scroll_item_prefab);
  //       new_node.parent = this.scroll_view_content;
  //       var controller = new_node.getComponent('RankItemController');
  //       controller.refresh(i, items_d[i]);
  //       this.cached_scroll_item.push(controller);
  //     }
  //   }
  // },

  set_data_success: result => {
    console.log('success' + result);
  },
  set_data_fail: result => {
    console.log('fail' + result);
  },

  get_friend_data_success(that) {
    return result => {
      console.log('好友信息', result);
      var data = result['data'];
      let arrList = [];
      for (var k in data) {
        var final_d = {};
        var item_d = data[k];
        var kv_list = item_d['KVDataList'];
        final_d['avatarUrl'] = item_d['avatarUrl'];
        final_d['nickname'] = item_d['nickname'];
        for (var kv in kv_list) {
          if (kv_list[kv]['key'] == 'max_score') {
            final_d['max_score'] = parseInt(kv_list[kv]['value']);
            break;
          }
        }
        arrList.push(final_d);
        // self.cached_data[item_d['openid']] = final_d;
      }
      //这里需要排序
      arrList.sort(that.createComparisonFunction('max_score'));
      that.rankListData = arrList;
      that.renderData(arrList);
    };
  },

  get_friend_data_fail: result => {
    console.log(result);
  },

  createComparisonFunction(propertyName) {
    return function(object1, object2) {
      var value1 = object1[propertyName];
      var value2 = object2[propertyName];
      if (value1 < value2) {
        return -1;
      } else if (value1 > value2) {
        return 1;
      } else {
        return 0;
      }
    };
  },

  renderData(data) {
    data.forEach((ele, i) => {
      this.ranklistView.removeAllChildren();

      let friendNode = cc.instantiate(this.peoplePrefab);
      this.ranklistView.addChild(friendNode);

      friendNode.x = this.ranklistView.width / 2;
      friendNode.y = -(80 + (friendNode.height / 2 + 20) * i);

      // set index
      let userIndex = friendNode.getChildByName('rank').getComponent(cc.Label);
      userIndex.string = i + 1;

      // set value
      let userValue = friendNode.getChildByName('score').getComponent(cc.Label);
      userValue.string = ele.max_score || 0;

      // set nickName
      let userName = friendNode.getChildByName('name').getComponent(cc.Label);
      userName.string = ele.nickName || ele.nickname;

      // set avatar
      cc.loader.load(
        {
          url: ele.avatarUrl,
          type: 'png'
        },
        (err, texture) => {
          if (err) console.error(err);
          let userIcon = friendNode
            .getChildByName('avatarUrl')
            .getComponent(cc.Sprite);
          userIcon.spriteFrame = new cc.SpriteFrame(texture);
        }
      );
    });
    // for (let i = 0; i < data.length; i++) {}
  }
});
